package leetcode;

/*
111. 二叉树的最小深度
给定一个二叉树，找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回它的最小深度  2.
*/

import java.util.ArrayList;
import java.util.List;

public class problems_111 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        node1.left = node2;
//        node1.right = node3;
//        node2.left = node4;
//        node2.right = node5;
        System.out.println(new Solution().minDepth(node1));
    }
    static public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    static class Solution {
        public int minDepth(TreeNode root) {
            if(null == root) return 0;
            if(null == root.right && null == root.left) return 1;
            List<TreeNode> current = new ArrayList<>();
            current.add(root);
            int floor = 0; // 层数

            // 逐层遍历
            while (1==1){
                floor++;
                List<TreeNode> next = new ArrayList<>();
                boolean back = false;
                for (int i = 0; i < current.size(); i++) {
                    if(null == current.get(i).left && null == current.get(i).right){
                        back = true;
                        break;
                    }
                    if(null != current.get(i).left) next.add(current.get(i).left);
                    if(null != current.get(i).right) next.add(current.get(i).right);
                }
                if(back) break;
                current = next;
            }
            return floor;
        }
    }
}